package com.atguigu.tingshu.order.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.date.DateUtil;
import cn.hutool.core.lang.Assert;
import cn.hutool.core.lang.Snowflake;
import cn.hutool.core.util.IdUtil;
import com.atguigu.tingshu.account.AccountFeignClient;
import com.atguigu.tingshu.album.AlbumFeignClient;
import com.atguigu.tingshu.common.constant.RedisConstant;
import com.atguigu.tingshu.common.constant.SystemConstant;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.rabbit.constant.MqConst;
import com.atguigu.tingshu.common.rabbit.service.RabbitService;
import com.atguigu.tingshu.common.result.Result;
import com.atguigu.tingshu.common.result.ResultCodeEnum;
import com.atguigu.tingshu.model.album.AlbumInfo;
import com.atguigu.tingshu.model.album.TrackInfo;
import com.atguigu.tingshu.model.order.OrderDerate;
import com.atguigu.tingshu.model.order.OrderDetail;
import com.atguigu.tingshu.model.order.OrderInfo;
import com.atguigu.tingshu.model.user.VipServiceConfig;
import com.atguigu.tingshu.order.helper.SignHelper;
import com.atguigu.tingshu.order.mapper.OrderDerateMapper;
import com.atguigu.tingshu.order.mapper.OrderDetailMapper;
import com.atguigu.tingshu.order.mapper.OrderInfoMapper;
import com.atguigu.tingshu.order.service.OrderInfoService;
import com.atguigu.tingshu.user.client.UserFeignClient;
import com.atguigu.tingshu.vo.account.AccountDeductVo;
import com.atguigu.tingshu.vo.album.AlbumStatVo;
import com.atguigu.tingshu.vo.order.OrderDerateVo;
import com.atguigu.tingshu.vo.order.OrderDetailVo;
import com.atguigu.tingshu.vo.order.OrderInfoVo;
import com.atguigu.tingshu.vo.order.TradeVo;
import com.atguigu.tingshu.vo.user.UserInfoVo;
import com.atguigu.tingshu.vo.user.UserPaidRecordVo;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.seata.spring.annotation.GlobalTransactional;
import kotlin.jvm.internal.Lambda;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

@Slf4j
@Service
@SuppressWarnings({"all"})
public class OrderInfoServiceImpl extends ServiceImpl<OrderInfoMapper, OrderInfo> implements OrderInfoService {

    @Autowired
    private OrderInfoMapper orderInfoMapper;

    @Autowired
    private UserFeignClient userFeignClient;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private AlbumFeignClient albumFeignClient;

    @Autowired
    private OrderDetailMapper orderDetailMapper;

    @Autowired
    private OrderDerateMapper orderDerateMapper;

    @Autowired
    private AccountFeignClient accountFeignClient;

    @Autowired
    private RabbitService rabbitService;

    /**
     * 订单结算（渲染订单结算页面三种不同的商品列表，包括：会员、专辑、声音）
     *
     * @param userId
     * @param tradeVo
     * @return
     */
    @Override
    public OrderInfoVo tradeData(Long userId, TradeVo tradeVo) {
        //1.创建订单VO响应对象
        OrderInfoVo orderInfoVo = new OrderInfoVo();

        //1.1 初始化相关的三个金额：原价、订单价、减免价格
        //TODO 这里价格必须是字符串，否则验签会失败
        //字符串格式精度更高，避免精度丢失
        BigDecimal originalAmount = new BigDecimal("0.00");
        BigDecimal orderAmount = new BigDecimal("0.00");
        BigDecimal derateAmount = new BigDecimal("0.00");

        //1.2 初始化商品列表和优惠列表
        List<OrderDetailVo> orderDetailVoList = new ArrayList<>();
        List<OrderDerateVo> orderDerateVoList = new ArrayList<>();

        //付款项目类型: 1001-专辑 1002-声音 1003-vip会员
        String itemType = tradeVo.getItemType();
        //2.TODO 处理购买项目类型为VIP会员的情况
        if (SystemConstant.ORDER_ITEM_TYPE_VIP.equals(itemType)) {
            //2.1 远程调用用户服务获取用户选择套餐信息
            VipServiceConfig vipServiceConfig = userFeignClient.getVIpServiceConfigById(tradeVo.getItemId()).getData();
            Assert.notNull(vipServiceConfig,
                    "用户{}选购的套餐{}不存在", userId, tradeVo.getItemId());
            //2.2 计算"商品"相关价格
            //原价
            originalAmount = vipServiceConfig.getPrice();
            //折后价
            orderAmount = vipServiceConfig.getDiscountPrice();
            //判断是否有减免
            if (originalAmount.compareTo(orderAmount) != 0) {
                derateAmount = originalAmount.subtract(orderAmount);
                //订单减免类型 1405-专辑折扣 1406-VIP服务折
                OrderDerateVo orderDerateVo = new OrderDerateVo();
                orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_VIP_SERVICE_DISCOUNT);
                orderDerateVo.setDerateAmount(derateAmount);
                orderDerateVo.setRemarks("VIP限时优惠价：" + derateAmount);
                orderDerateVoList.add(orderDerateVo);

            }

            //2.3 封装商品明细及优惠明细列表
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemId(tradeVo.getItemId());
            orderDetailVo.setItemName(vipServiceConfig.getName());
            orderDetailVo.setItemUrl(vipServiceConfig.getImageUrl());
            orderDetailVo.setItemPrice(originalAmount);
            orderDetailVoList.add(orderDetailVo);


        } else if (SystemConstant.ORDER_ITEM_TYPE_ALBUM.equals(itemType)) {
            //3.TODO 处理购买项目类型为专辑的情况
            //3.1 远程调用用户服务，判断当前用户是否购买过当前专辑
            Long albumId = tradeVo.getItemId();
            Boolean flag = userFeignClient.isPaidAlbum(albumId).getData();
            if (flag) {
                throw new GuiguException(231, "用户已经购买过该专辑，不能重复购买");
            }

            //3.2 远程调用专辑服务获取专辑信息，得到价格和折扣信息
            AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(albumId).getData();
            Assert.notNull(albumInfo, "专辑{}不存在", albumId);

            //3.2.1 获取专辑价格
            originalAmount = albumInfo.getPrice();
            //首先令订单价等于原价
            orderAmount = originalAmount;

            //3.2.2 获取专辑折扣
            //普通用户折扣
            BigDecimal discount = albumInfo.getDiscount();
            //vip用户折扣
            BigDecimal vipDiscount = albumInfo.getVipDiscount();

            //3.3 远程调用用户服务获取用户身份
            UserInfoVo userInfoVo = userFeignClient.getUserInfoVo(userId).getData();
            Assert.notNull(userInfoVo, "用户{}不存在", userId);
            //默认用户不是vip
            Boolean isVip = false;
            //当vip标识为1并且vip的到期时间大于当前时间，则该用户是vip
            if (userInfoVo.getIsVip().intValue() == 1
                    && userInfoVo.getVipExpireTime().after(new Date())) {
                isVip = true;
            }


            //3.4 计算相关价格
            //3.4.1 判断是否是普通用户并且专辑是否设置了用户折扣
            if (isVip == false && new BigDecimal("-1").compareTo(discount) != 0) {
                orderAmount = originalAmount
                        .multiply(discount)
                        .divide(new BigDecimal("10"), 2, BigDecimal.ROUND_HALF_UP);
                derateAmount = originalAmount.subtract(orderAmount);
            }

            //3.4.2 判断是否是VIP用户并且专辑是否设置了会员折扣
            if (isVip && new BigDecimal("-1").compareTo(vipDiscount) != 0) {
                orderAmount = originalAmount
                        .multiply(vipDiscount)
                        .divide(new BigDecimal("10"), 2, BigDecimal.ROUND_HALF_UP);
                derateAmount = originalAmount.subtract(orderAmount);
            }

            //3.5 封装商品明细以及优惠明细列表
            OrderDetailVo orderDetailVo = new OrderDetailVo();
            orderDetailVo.setItemId(albumId);
            orderDetailVo.setItemName("专辑：" + albumInfo.getAlbumTitle());
            orderDetailVo.setItemUrl(albumInfo.getCoverUrl());
            orderDetailVo.setItemPrice(originalAmount);
            orderDetailVoList.add(orderDetailVo);


            //原价和实际价格不一样，说明有折扣
            if (originalAmount.compareTo(orderAmount) != 0) {
                OrderDerateVo orderDerateVo = new OrderDerateVo();
                orderDerateVo.setDerateType(SystemConstant.ORDER_DERATE_ALBUM_DISCOUNT);
                orderDerateVo.setDerateAmount(derateAmount);
                orderDerateVo.setRemarks("专辑减免价格：" + derateAmount);
                orderDerateVoList.add(orderDerateVo);

            }


        } else if (SystemConstant.ORDER_ITEM_TYPE_TRACK.equals(itemType)) {
            //4.TODO 处理购买项目为声音的情况
            //4.1 远程调用专辑服务获取用户待购买声音列表-将声音列表作为待结算商品展示到结算页
            Integer trackCount = tradeVo.getTrackCount();
            Long trackId = tradeVo.getItemId();
            List<TrackInfo> trackInfoList = albumFeignClient.findPaidTrackInfoList(trackId, trackCount).getData();
            Assert.notNull(trackInfoList, "不满足待结算的声音列表");

            //4.2 远程调用专辑服务获取专辑信息，得到价格(声音不支持折扣)
            Long albumId = trackInfoList.get(0).getAlbumId();
            AlbumInfo albumInfo = albumFeignClient.getAlbumInfo(albumId).getData();
            BigDecimal price = albumInfo.getPrice();

            //4.3 计算相关价格(原价=订单价)
            originalAmount = price.multiply(BigDecimal.valueOf(trackInfoList.size()));
            orderAmount = originalAmount;
            //4.4 封装商品明细列表即可

            orderDetailVoList = trackInfoList.stream()
                    .map(trackInfo -> {
                        OrderDetailVo orderDetailVo = new OrderDetailVo();
                        orderDetailVo.setItemId(trackInfo.getId());
                        orderDetailVo.setItemName("声音：" + trackInfo.getTrackTitle());
                        orderDetailVo.setItemUrl(trackInfo.getCoverUrl());
                        orderDetailVo.setItemPrice(price);
                        return orderDetailVo;
                    }).collect(Collectors.toList());

        }

        //5.响应订单VO对象
        //5.1 封装订单vo中价格相关属性
        orderInfoVo.setOriginalAmount(originalAmount);
        orderInfoVo.setOrderAmount(orderAmount);
        orderInfoVo.setDerateAmount(derateAmount);

        //5.2 封装订单vo中商品相关的两个列表
        orderInfoVo.setOrderDetailVoList(orderDetailVoList);
        orderInfoVo.setOrderDerateVoList(orderDerateVoList);
        //5.3 TODO 封装其他属性-项目购买类型、本次订单确认流水号、时间戳以及姓名。
        //5.3.1 防止订单利用浏览器回退造成订单重复提交，通过生成唯一流水号避免这种情况
        String tradeNo = IdUtil.randomUUID();
        String key = RedisConstant.ORDER_TRADE_NO_PREFIX + userId;
        //5.3.2 将本次订单流水号的值存入到Redis中，并且设置过期时间为5分钟。
        redisTemplate.opsForValue().set(key, tradeNo, 5, TimeUnit.MINUTES);
        //5.3.3 将订单流水号封装到OrderInfoVo中，返回给客户端。
        orderInfoVo.setTradeNo(tradeNo);

        //5.4 封装订单中的项目类型
        orderInfoVo.setItemType(itemType);

        //5.5 封装时间戳以及签名
        orderInfoVo.setTimestamp(System.currentTimeMillis());
        //5.5.1 将订单vo转为map
        //TODO 结算页无法确定用户支付方式，将付款方式payWay去掉不需要参与加签规则。
        //是否转换为下划线，是否忽略值为空的字段
        Map<String, Object> map = BeanUtil.beanToMap(orderInfoVo, false, true);

        //5.5.2 将订单Map转为签名
        String sign = SignHelper.getSign(map);
        orderInfoVo.setSign(sign);

        return orderInfoVo;

    }

    /**
     * 订单提交(包含两种付款方式 1.余额支付 2.微信支付)
     *
     * @param userId
     * @param orderInfoVo
     * @return
     */
    @Override
    //全局异常事务注解
    @GlobalTransactional(rollbackFor = Exception.class)
    public Map<String, String> submitOrder(Long userId, OrderInfoVo orderInfoVo) {
        //1.业务校验：校验流水号是否相同，避免用户通过小程序回退按钮造成订单重复提交
        //1.1 获取redis中流水号值跟前端确认页的流水号值进行比较
        //1.2 如果二者不同则业务终止，如果相同则删除Redis流水号，业务继续。
        //1.3 执行lua脚本完成判断，确保语句的原子性
        //1.3.1 定义lua脚本
        String key = RedisConstant.ORDER_TRADE_NO_PREFIX + userId;
        String script = """
                if redis.call("get",KEYS[1]) == ARGV[1]
                then
                    return redis.call("del",KEYS[1])
                else
                    return 0
                end
                """;
        //1.3.2 创建脚本对象封装lua脚本
        //这是线程不安全的写法
        /*String value = (String) redisTemplate.opsForValue().get(key);
            if(value.equals(orderInfoVo.getTradeNo())){
                redisTemplate.delete(key);
        }*/

        //这是线程安全的写法
        DefaultRedisScript redisScript = new DefaultRedisScript(script, Boolean.class);
        Boolean flag = (Boolean) redisTemplate.execute(redisScript, Arrays.asList(key), orderInfoVo.getTradeNo());
        if (!flag) {
            throw new GuiguException(500, "订单流水号验证失败");
        }

        //2.业务校验：校验签名是否一致，避免订单确认页篡改订单相关信息
        //2.1 将订单VO转为Map集合
        //TODO 订单结算页生成签名的时候，payWay并未参与加签中，在验签之前，需要将payWay去掉
        Map<String, Object> map = BeanUtil.beanToMap(orderInfoVo);
        map.remove("payWay");

        //2.2 调用签名工具类完成签名验证
        SignHelper.checkSign(map);

        //3.核心业务1：保存订单相关信息 此时订单状态为未支付状态
        OrderInfo orderInfo = this.saveOrderInfo(orderInfoVo, userId);


        //4.判断付款方式 如果是余额支付，则需要扣减余额，扣减成功以后将订单状态改为已支付并且完成虚拟物品的发货
        String payWay = orderInfoVo.getPayWay();
        if (SystemConstant.ORDER_PAY_ACCOUNT.equals(payWay)) {
            //4.1 远程调用账户服务完成余额扣减，发生异常则进行全局异常回滚。
            //4.1.1 创建扣减余额vo对象
            AccountDeductVo accountDeductVo = new AccountDeductVo();
            accountDeductVo.setOrderNo(orderInfo.getOrderNo());
            accountDeductVo.setUserId(orderInfo.getUserId());
            accountDeductVo.setAmount(orderInfo.getOrderAmount());
            accountDeductVo.setContent(orderInfo.getOrderTitle());

            Result result = accountFeignClient.checkAndDeduct(accountDeductVo);
            //4.1.2 判断业务状态码是否是200
            if (!result.getCode().equals(ResultCodeEnum.SUCCESS.getCode())) {
                throw new GuiguException(ResultCodeEnum.ACCOUNT_LESS);
            }

            //4.2 余额扣减成功，将订单状态改为已支付
            orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_PAID);
            orderInfoMapper.updateById(orderInfo);
            //4.3 余额扣减成功，远程调用用户服务完成虚拟物品发货
            UserPaidRecordVo userPaidRecordVo = new UserPaidRecordVo();
            userPaidRecordVo.setOrderNo(orderInfo.getOrderNo());
            userPaidRecordVo.setUserId(orderInfo.getUserId());
            userPaidRecordVo.setItemType(orderInfo.getItemType());
            //4.3.2 封装购买项目id列表，有可能是会员或者专辑或者声音id
            List<OrderDetailVo> orderDetailVoList = orderInfoVo.getOrderDetailVoList();
            if (CollectionUtil.isNotEmpty(orderDetailVoList)) {
                List<Long> itemIdList = orderDetailVoList.stream()
                        .map(OrderDetailVo::getItemId)
                        .collect(Collectors.toList());
                userPaidRecordVo.setItemIdList(itemIdList);
            }
            //4.3.3 远程调用服务，完成虚拟物品的发货
            userFeignClient.savePaidRecord(userPaidRecordVo);
            result = userFeignClient.savePaidRecord(userPaidRecordVo);
            if (!result.getCode().equals(ResultCodeEnum.SUCCESS.getCode())) {
                throw new GuiguException(500, "虚拟物品发货异常");
            }


        } else if (SystemConstant.ORDER_PAY_WAY_WEIXIN.equals(payWay)) {
            //5.判断付款方式 如果是微信支付，避免用户超时未支付，需要发送延迟消息完成延迟关单
            rabbitService.sendDelayMessage(
                    MqConst.EXCHANGE_CANCEL_ORDER,
                    MqConst.ROUTING_CANCEL_ORDER,
                    orderInfo.getId(),
                    MqConst.CANCEL_ORDER_DELAY_TIME);

            




        }


        //6.响应map封装订单编号
        String orderNo = orderInfo.getOrderNo();
        Map<String, String> resultMap = new HashMap<>();
        resultMap.put("orderNo", orderNo);
        return resultMap;

    }

    /**
     * 根据订单号获取订单详细信息(包括订单明细以及优惠列表)
     *
     * @param orderNo
     * @return
     */
    @Override
    public OrderInfo getOrderInfo(String orderNo) {
        //1.根据订单编号查询订单信息
        LambdaQueryWrapper<OrderInfo> orderInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderInfoLambdaQueryWrapper.eq(OrderInfo::getOrderNo, orderNo);
        OrderInfo orderInfo = orderInfoMapper.selectOne(orderInfoLambdaQueryWrapper);
        Assert.notNull(orderInfo, "订单不存在");

        Long orderId = orderInfo.getId();

        //2.根据订单id查询订单明细列表
        LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, orderId);
        List<OrderDetail> orderDetailList = orderDetailMapper.selectList(orderDetailLambdaQueryWrapper);
        orderInfo.setOrderDetailList(orderDetailList);

        //3.根据订单id查询订单优惠列表
        LambdaQueryWrapper<OrderDerate> orderDerateLambdaQueryWrapper = new LambdaQueryWrapper<>();
        orderDerateLambdaQueryWrapper.eq(OrderDerate::getOrderId, orderId);
        List<OrderDerate> orderDerateList = orderDerateMapper.selectList(orderDerateLambdaQueryWrapper);
        orderInfo.setOrderDerateList(orderDerateList);

        return orderInfo;
    }

    /**
     * 分页获取当前用户的订单列表
     *
     * @param orderInfoPage
     * @param userId
     * @return
     */
    @Override
    public Page<OrderInfo> getUserOrderByPage(Page<OrderInfo> orderInfoPage, Long userId) {
//        //方式一：分页查询订单列表，遍历订单再获取订单明细
//        //1.查询订单列表
//        LambdaQueryWrapper<OrderInfo> orderInfoLambdaQueryWrapper = new LambdaQueryWrapper<>();
//        orderInfoLambdaQueryWrapper.eq(OrderInfo::getUserId, userId);
//        orderInfoPage = orderInfoMapper.selectPage(orderInfoPage, orderInfoLambdaQueryWrapper);
//
//        //2.遍历订单中获取订单中的明细列表
//        orderInfoPage.getRecords().forEach(orderInfo -> {
//            //2.根据订单id查询订单明细列表
//            LambdaQueryWrapper<OrderDetail> orderDetailLambdaQueryWrapper = new LambdaQueryWrapper<>();
//            orderDetailLambdaQueryWrapper.eq(OrderDetail::getOrderId, orderInfo.getId());
//            List<OrderDetail> orderDetailList = orderDetailMapper.selectList(orderDetailLambdaQueryWrapper);
//            orderInfo.setOrderDetailList(orderDetailList);
//        });
//        return orderInfoPage;

        //方式二：通过动态sql查询订单以及订单明细
        return orderInfoMapper.getUserOrderByPage(orderInfoPage, userId);

    }

    /**
     * 根据订单状态，如果是未支付则取消订单
     *
     * @param orderId
     */
    @Override
    public void cancelOrder(Long orderId) {
        //1.根据订单id查询订单状态，判断状态
        OrderInfo orderInfo = orderInfoMapper.selectById(orderId);
        Assert.notNull(orderInfo, "订单不存在");

        //2.如果订单是未支付，则将订单修改为关闭
        if (SystemConstant.ORDER_STATUS_UNPAID.equals(orderInfo.getOrderStatus())) {
            orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_CANCEL);
            orderInfoMapper.updateById(orderInfo);
        }

    }

    /**
     * 保存订单信息
     *
     * @param orderInfoVo 订单vo对象
     * @param userId      用户id
     * @return
     */
    private OrderInfo saveOrderInfo(OrderInfoVo orderInfoVo, Long userId) {
        //1.保存订单，得到订单id
        //1.1 将提交的订单vo对象转为订单po对象
        OrderInfo orderInfo = BeanUtil.copyProperties(orderInfoVo, OrderInfo.class);
        //1.2 手动为其他属性赋值
        //1.2.1 用户id
        orderInfo.setUserId(userId);
        //1.2.2 订单状态，未支付
        //订单状态 0901-正常 0902-已支付 0903-已取消
        orderInfo.setOrderStatus(SystemConstant.ORDER_STATUS_UNPAID);
        //1.2.3 订单标题，从订单明细中的第一条购买项目中获取即可
        List<OrderDetailVo> orderDetailVoList = orderInfoVo.getOrderDetailVoList();
        if (CollectionUtil.isNotEmpty(orderDetailVoList)) {
            String itemName = orderDetailVoList.get(0).getItemName();
            orderInfo.setOrderTitle(itemName);
        }
        //1.2.4 订单编号，商户系统中全局唯一 形式：订单日期+雪花算法
        String orderNo = DateUtil.today().replaceAll("-", "") + IdUtil.getSnowflakeNextId();
        orderInfo.setOrderNo(orderNo);
        //1.3 保存订单，得到订单id
        orderInfoMapper.insert(orderInfo);
        Long orderId = orderInfo.getId();

        //2.保存订单明细，将订单明细关联订单id
        if (CollectionUtil.isNotEmpty(orderDetailVoList)) {
            orderDetailVoList.stream()
                    .forEach(orderDetailVo -> {
                        OrderDetail orderDetail = BeanUtil.copyProperties(orderDetailVo, OrderDetail.class);
                        orderDetail.setOrderId(orderId);
                        orderDetailMapper.insert(orderDetail);
                    });
        }

        //3.保存优惠明细，将优惠明细关联订单id
        List<OrderDerateVo> orderDerateVoList = orderInfoVo.getOrderDerateVoList();
        if (CollectionUtil.isNotEmpty(orderDerateVoList)) {
            orderDerateVoList.stream()
                    .forEach(orderDerateVo -> {
                        OrderDerate orderDerate = BeanUtil.copyProperties(orderDerateVo, OrderDerate.class);
                        orderDerate.setOrderId(orderId);
                        orderDerateMapper.insert(orderDerate);
                    });
        }
        return orderInfo;

    }
}
